package com.lucky.tjs.config;

import com.dangdang.ddframe.job.api.ElasticJob;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.lucky.tjs.annotation.ElasticJobConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;

import javax.annotation.Resource;

/**
 * 容器启动之后，初始化所有 elastic-job 任务
 *  不能使用@Component  因为没有扫描组件
 * @author tianjiashu
 */
public class EljobPostProcessor implements BeanPostProcessor {

    @Resource
    private CoordinatorRegistryCenter regCenter;

    @Resource
    private InitJobSchedulerHandler initJobSchedulerUtil;

    private final Logger log = LoggerFactory.getLogger(EljobPostProcessor.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ElasticJobConfig config = AnnotationUtils.findAnnotation(bean.getClass(), ElasticJobConfig.class);
        /*
            如果这个Bean被 注解ElasticJobConfig修饰，并且实现了ElasticJob接口
        */
        if (config != null) {
            log.info("In EljobPostProcessor init: {}, {}", beanName, bean.getClass().getName());
            if(bean instanceof ElasticJob){
                ElasticJob elasticJob = (ElasticJob)bean;
                LiteJobConfiguration jobConfiguration = initJobSchedulerUtil.getJobConfiguration( config, elasticJob);
                JobScheduler jobScheduler = new SpringJobScheduler(elasticJob, regCenter, jobConfiguration);
                jobScheduler.init();
            }
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }



}
